<?php

class PageWidgetController extends BackOfficeController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>FSM::run('Cms.PageWidget.get', array('id'=>$id))->model,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($container)
	{
        $page_id = $this->get('page_id', 0);
        $revision_id = $this->get('revision_id', 0);
        $templateContentId = $this->get('template_content_id', 0);
        
        if (Yii::app()->request->getIsPostRequest() && ($widgetId = $this->post('widget',0)) > 0) {
            $widget = CmsWidget::model()->findByPk($widgetId);
            $this->redirect($this->createUrl('/'.$widget->path.'/update', array(
                'page_id' => $this->post('page_id'),
                'widget_id' => $widgetId,
                'revision_id' => $this->post('revision_id'),
                'template_content_id' => $templateContentId,
                'container' => $this->post('container'),
            )));
        }
        
        Yii::app()->theme = 'new_admin';
        $this->layout = '//layouts/box';
        
        $this->render('create');
	}
    
    public function actionUpdate($container)
    {
        $page_id = $this->get('page_id', 0);
        $revision_id = $this->get('revision_id', 0);
        $templateContentId = $this->get('template_content_id', 0);
        if (Yii::app()->request->IsPostRequest)
        {
            $layout = $this->post('layout', '');
            //create new
            $isNew = $this->post('action', 0);
            if ($isNew == 0)
            {
                $url = array(
                    '/Cms/admin/widget/updateInstance',
                    'layout'=>$layout,
                    'page_id'=>(int) $page_id,
                    'revision_id'=>(int) $revision_id,
                    'container'=>$container,
                    'id'=>(int) $this->post('widget_id'),
                    'instanceId'=>0,
                    'widget_layout_id'=>(int) $_POST['PageWidget']['widget_layout_id'],
                );
                $this->redirect($url);
            }
            else
            {
                $result = FSM::run('Cms.PageWidget.save', $_POST);
                $model = $result->model;
                if (! $result->hasErrors())
                {
                    $this->message = Yii::t('Core','Item has been saved successfully.');
                    if (!empty($layout) && $layout == 'popup' && !in_array($model->container, array('cms-header', 'cms-footer')))
                    {
                        FSM::run('Cms.PageWidget.dynamicAddWidget', array('page_widget_id'=>$model->id));
                    }
                    else
                        $this->refresh();
                }
                else
                    $this->refresh();
            }
        }
        else
        {
            $model = new PageWidget();
            $model->status = 1;
            $model->page_id = (int) $page_id;
            $model->revision_id = (int) $revision_id;
            $model->container = (string) $container;
        }
        
        $widgetId = Yii::app()->request->getParam('widget_id', 0);
        $type = Yii::app()->request->getParam('type', 'all');
        if (empty($type))
            $type = 'all';
        Yii::trace('data $widgetId:'.$widgetId.', $type'.$type, 'filter-widget');
        /*$dataProvider = FSM::run('Cms.widgetLayout.getByType', array('type'=>$type, 'widget_id'=>$widgetId))->dataProvider;
        Yii::trace('$dataProvider: '.$dataProvider->totalItemCount, 'filter-widget');*/
        
        $types = WidgetDefinition::model()->getTypeOptions();
        $criteria = new CDbCriteria();
        $criteria->select = array('name', 'id');
        $criteria->order = 't.name';
        $widgets = WidgetDefinition::model()->findAll($criteria);
        $widgets = CHtml::listData($widgets, 'id', 'name');
        
        $this->render('update', array(
            'model'=>$model,
//            'dataProvider'=>$dataProvider,
            'types'=>$types,
            'widgets'=>$widgets,
        ));
    }
    
    /*public function actionWidgetData($widget_id, $widget_layout_id, $page_id)
    {
        $models = FSM::run('Cms.widgetData.getList', array(
            'widget_id'=>(int) $widget_id,
            'widget_layout_id'=>(int) $widget_layout_id,
            'status'=>1,
        ))->models;
        $data = array();
        if (count($models))
        {
            foreach ($models as $model)
            {
                $data[] = array(
                    'id'=>$model->id,
                    'name'=>$model->name,
                );
            }
        }
        echo CJSON::encode($data);
        Yii::app()->end();
    }*/

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            if (($id = $this->get('id',null)) !== null) {
                $ids = is_numeric($id) ? array($id) : explode(',',$id);
                
                // delete one or multiple objects given the list of object IDs
                $result = FSM::run('Cms.PageWidget.delete', array('ids' => $ids));
                if ($result->hasErrors()) {
                    echo $result->getError('ErrorCode');
                } elseif(!Yii::app()->request->isAjaxRequest) {
                    // only redirect user to the admin page if it is not an AJAX request
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                }
            } else {
                throw new CHttpException(400,Yii::t('Core','Cannot delete item with the given ID.'));
            }
        } else {
            throw new CHttpException(400,Yii::t('Core','Invalid request. Please do not repeat this request again.'));
        }
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        $this->actionAdmin();
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
        $model=new PageWidget('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['PageWidget']))
            $model->attributes=$_GET['PageWidget'];

        $this->render('admin',array(
            'model'=>$model,
        ));
	}
    
    public function actionNewData()
    {
        $models = FSM::run('Cms.WidgetDefinition.getList', array('status'=>true))->models;
        if (count($models))
            $widgets = CHtml::listData($widgets, 'id', 'name');
            
        $this->render('newData', array('models'=>$models));
    }
    
    public function actionExistData()
    {
        $this->render('existData');
    }
    
    public function actionHiddenContainer($page_id, $revision_id, $type)
    {
        $header = FSM::run('Cms.PageWidget.getItemsHiddenContainer', array(
            'page_id'=>$page_id, 
            'revision_id'=>$revision_id, 
            'type'=>'cms-header',
        ))->items;
        $footer = FSM::run('Cms.PageWidget.getItemsHiddenContainer', array(
            'page_id'=>$page_id,
            'revision_id'=>$revision_id,
            'type'=>'cms-footer',
        ))->items;
        $this->render('hiddenContainer', array(
            'header'=>$header,
            'footer'=>$footer,
            'page_id'=>$page_id,
            'revision_id'=>$revision_id
        ));
    }

    /**
     * List pages that are using a specific widget.
     */
    public function actionList($widget_id)
    {
        $siteId = Yii::app()->cmsManager->site['id'];
        $workflows = FSM::run('Cms.workflow.getBySite', array('site_id'=>$siteId))->models;
        if (count($workflows))
            $workflows = CHtml::listData($workflows, 'id', 'name');
        $result = FSM::run('Cms.workflow.getFinalWorkflowBySiteId', array('site_id'=>$siteId));
        $workflowSelected = 0;
        if (!$result->hasErrors())
            $workflowSelected = $result->model->id;
        
        $model=new PageWidget('searchByWidget');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['PageWidget']))
            $model->attributes=$_GET['PageWidget'];
        elseif ($workflowSelected)
            $model->workflowId = $workflowSelected;

        $this->render('list',array(
            'model'=>$model,
            'siteId'=>$siteId,
            'widgetId'=>$widget_id,
            'workflows'=>$workflows,
            'workflowSelected'=>$workflowSelected,
        ));
    }
    
    public function actionLayout()
    {
        
        $page_widget_id = (int) $this->get('page_widget_id', 0);
        $selected = (int) $this->get('widget_layout_id', 0);
        
        if (isset($_POST['widget_layout_id']) && $page_widget_id)
        {
            $selected = (int) $_POST['widget_layout_id'];
            Yii::trace('$_GET '.CVarDumper::dumpAsString($_GET), 'PageWidget');
            Yii::trace('$_POST '.CVarDumper::dumpAsString($_POST), 'PageWidget');
            Yii::trace('$selected '.$selected, 'PageWidget');
            PageWidget::model()->updateByPk($page_widget_id, array('widget_layout_id'=>$selected));
            Yii::app()->clientScript->registerScript(__CLASS__.'ClosePopup', 'parent.location = parent.location.href.replace(/\#.*/, "");');
        }
        
        if (!$selected)
        {
            $pageWidget = PageWidget::model()->findByPk($page_widget_id);
            if (is_object($pageWidget))
                $selected = (int) $pageWidget->widget_layout_id;
        }
        
        $layout = WidgetLayout::model()->findByPk($selected);
        if (is_object($layout))
        {
            $criteria = new CDbCriteria();
            $criteria->compare('widget_id', $layout->widget_id);
            $criteria->compare('status', true);
            $criteria->order = 'name DESC';
            $data = WidgetLayout::model()->findAll($criteria);
            if (count($data))
            {
                $data = CHtml::listData($data, 'id', 'name');
                foreach ($data as $index => $name)
                {
                    $data[$index] = CHtml::image(Yii::app()->themeManager->baseUrl.'/serta/images/widget-default-layout.png', $name).CHtml::tag('span', array(), $name);
                }
            }
            $this->render('layout', array('selected'=>$selected, 'data'=>$data));
        }
    }
}